import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class MessageResolverFactory {

    private static final MessageResolverFactory resolverFactory = new MessageResolverFactory();

    private static final List<Resolver> resolvers = new CopyOnWriteArrayList<>();


    private MessageResolverFactory() {
    }

    static {
        resolverFactory.registerResolver(new RequestMessageResolver());
        resolverFactory.registerResolver(new ResponseMessageResolver());
        resolverFactory.registerResolver(new PingMessageResolver());
        resolverFactory.registerResolver(new PongMessageResolver());
        resolverFactory.registerResolver(new LoginMessageResolver());
    }

    public static MessageResolverFactory getInstance() {
        return resolverFactory;
    }

    public void registerResolver(Resolver resolver) {
        resolvers.add(resolver);
    }

    public Resolver getMessageResolver(IMessage iMessage) {
        for (Resolver resolver : resolvers) {
            if (resolver.support(iMessage)) {
                return resolver;
            }
        }
        throw new RuntimeException(" cannot find resolver,message type :" + iMessage.getType());
    }

}
